package com.example.shiro;

import com.example.MySimpleByteSource;
import com.example.Service.UserService;
import com.example.mapper.SysRoleRightMapper;
import com.example.pojo.SysRoleRight;
import com.example.pojo.Vo.SysUserVo;
import com.sun.crypto.provider.HmacMD5;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
 * 域
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

     @Resource
     private SysRoleRightMapper sysRoleRightMapper;

     /**
      * 授权
      * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SysUserVo user =(SysUserVo) principalCollection.getPrimaryPrincipal();

        List<SysRoleRight> roleRights = userService.getRoleRightListById(user.getUsrRoleId());

        List<String> stringList = new ArrayList<>();

        for (SysRoleRight sysRoleRight : roleRights) {
            stringList.add(sysRoleRight.getRfRightCode());
        }

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        simpleAuthorizationInfo.addStringPermissions(stringList);

        return simpleAuthorizationInfo;
    }


    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String usrName = (String) authenticationToken.getPrincipal();
        SysUserVo user = userService.findUserByUsrName(usrName);
        if(user==null){
            throw new LockedAccountException();
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,
                user.getUsrPassword(),
//                ByteSource.Util.bytes("czkt"),
                new MySimpleByteSource("czkt"),
                getName()
        );

        return info;
    }


}
